package com.netease.service;

import com.netease.common.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by dongle on 2017/2/22.
 */
@Service
public class AccessTokenService {
    private static String generateTokenUrl = "https://open.c.163.com/api/v1/token";
    @Value("${app_key}")
    private String app_key;

    @Value("${app_secret}")
    private String app_secret;

    private volatile String token;
    private volatile boolean isTokenAvalabel;
    private Object needRefreshToken = new Object();
    private Object tokenAvalable = new Object();

    private String expires_in;

    public void refreshToken(){
        synchronized (needRefreshToken){
            needRefreshToken.notifyAll();
        }
    }
    public String getToken() {
        synchronized(this){
            while(!isTokenAvalabel){
                try {
                    this.wait();
                    System.out.println("wait finished!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return token;
        }
    }

//    public AccessTokenService(){
//        new Thread(){
//            @Override
//            public void run() {
//
//            }
//        }.start();
//    }

    public void startTokenService(){
        AccessTokenService localThis = this;
        new Thread(){
            @Override
            public void run() {
                do {
                    String postContent = String.format("{\"app_key\":\"%s\", \"app_secret\":\"%s\"}", app_key, app_secret);
                    String response = null;
                    try {
                        response = HttpUtil.getInstance().commonPost(generateTokenUrl, null, postContent);
                    } catch (IOException e) {
                        e.printStackTrace();
                        //break;
                    }
                    JacksonJsonParser parser = new JacksonJsonParser();
                    Map<String, Object> jsonMap = parser.parseMap(response);
                    try {
                        sleep(15000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    token = (String) jsonMap.get("token");
                    isTokenAvalabel = true;

                    System.out.println("this:"+this);
                    System.out.println("localThis:"+localThis);
                    synchronized (localThis){
                        localThis.notifyAll();
                    }

                    String expireStr = (String) jsonMap.get("expires_in");
                    Integer expireSecends = 30000;//Integer.valueOf(expireStr);

                    try {
                        synchronized (needRefreshToken){
                            needRefreshToken.wait((expireSecends-2));
                         }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                } while (true);
            }
        }.start();

    }
//    public void generateAccessToken() throws IOException {
//        String postContent = String.format("{\"app_key\":\"%s\", \"app_secret\":\"%s\"}", app_key, app_secret);
//        String response = HttpUtil.getInstance().commonPost(generateTokenUrl, null, postContent);
//        JacksonJsonParser parser = new JacksonJsonParser();
//        Map<String, Object> jsonMap = parser.parseMap(response);
//        token = (String) jsonMap.get("token");
//        expires_in = (String) jsonMap.get("expires_in");
//    }
}
